package cn.gongxi.weibo.controller;

import cn.gongxi.weibo.base.utils.CacheUtil;
import cn.gongxi.weibo.common.response.JsonResult;
import cn.gongxi.weibo.pojo.dto.WeiboDTO;
import cn.gongxi.weibo.pojo.entity.Weibo;
import cn.gongxi.weibo.pojo.mapper.WeiboMapper;
import cn.gongxi.weibo.pojo.vo.UserVO;
import cn.gongxi.weibo.pojo.vo.WeiboDetailVO;
import cn.gongxi.weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "02.微博模块")
@RestController
@RequestMapping("/v1/weibo/")
@Validated
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    //
//    @Autowired
//    private RedisTemplate<String, Serializable> redisTemplate;

    // 自动装配类【自己创建的工具类  掉用方法方便】
    @Autowired
    private CacheUtil cacheUtil;


    @ApiOperation(value = "发布微博")
    @PostMapping("insert")
    public JsonResult  insertWeibo(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session){
        // 获取用户的登录状态
        UserVO userVO = (UserVO) session.getAttribute("user");

//        if (userVO == null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }


        // 插入接口
        log.debug("weiboDTO = " + weiboDTO + ", session = " + session);
        // System.out.println("weiboDTO = " + weiboDTO + ", session = " + session);
        long userId = userVO.getId();
        System.out.println("userId = " + userId);

        // 传入实体类
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setUserId(userId);
        weibo.setCreated(new Date());

        weiboMapper.insertWeibo(weibo);
        return JsonResult.success();
    }

    @ApiOperation(value = "获取微博列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex(){
        /*
        1、先到redis中查看首页缓存数据(get)；
          如果存在   直接返回
          如果不存在
            到数据库中查询，
            然后插入到redis中(set)
            返回响应

         redis中的首页数据结构 ：{
            "weibo_index":List<WeiboIndexVO>
         }
         */


//        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
//        ops.get("weibo_index");
//        Serializable weiboIndex = ops.get("weibo_index");

        Serializable weiboIndex = cacheUtil.get("weibo_index");
        if (weiboIndex == null){
            // mysql中查询
            List<WeiboIndexVO> weiboIndexVOList = weiboMapper.selectIndex();
            log.debug("首页数据来自mysql " + weiboIndexVOList);
            // 第一个参数  存的数据  第二个参数  过期时间
//            ops.set("weibo_index", (Serializable) weiboIndexVOList,30, TimeUnit.SECONDS);
            // 利用封装好的工具类
            cacheUtil.set("weibo_index", (Serializable) weiboIndexVOList,30);
            return JsonResult.success(weiboIndexVOList);
        }

        log.debug("首页数据来自redis缓存数据库");
        return JsonResult.success(weiboIndex);
    }

    @ApiOperation(value = "通过id获取微博详情")
    @GetMapping("selectById")

    /*
    @RequestParam(value = "id",required = true)注解
    说明其是一个请求参数
    从请求参数中获取id的值，如果id的值为空，则抛出IllegalArgumentException异常

     */
    public JsonResult selectById(@Range(min = 1,max = 500, message = "id在1-500之间") @RequestParam long id)  {  // @RequestParam(value = "id",required = true) 说明其是一个请求参数
        if(id<0){
            throw new IllegalArgumentException("id不能小于0");
        }
        log.debug("id = " + id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        log.debug("weiboDetailVO = " + weiboDetailVO);
        return JsonResult.success(weiboDetailVO);
    }



}
